package com.boge.ai.service;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class OpenMyBlogTool {
    // 目标博客首页 URL
    private static final String BLOG_HOME_URL = "https://blog.csdn.net/qq_38526573";

    @Tool(name = "get-blog-info", description = "获取博客信息")
    public String getAuthorInfo() {
        OkHttpClient client = new OkHttpClient();
        // 1. 发送 HTTP 请求获取网页 HTML
        String htmlContent = getHtmlContent(client, BLOG_HOME_URL);
        if (htmlContent == null || htmlContent.isEmpty()) {
            System.err.println("无法获取网页内容");
            return "无法获取网页内容";
        }
        return htmlContent;
    }


    /**
     * 发送 HTTP GET 请求，获取网页 HTML 内容
     */
    private String getHtmlContent(OkHttpClient client, String url) {
        Request request = new Request.Builder()
                .url(url)
                // 模拟浏览器请求头，避免被识别为爬虫
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                return response.body().string(); // 返回 HTML 字符串
            } else {
                System.err.println("请求失败，响应码：" + response.code());
                return null;
            }
        } catch (IOException e) {
            System.err.println("网络请求异常：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

}

